package com.winhxd.b2c.message.sms.process;


import com.winhxd.b2c.common.constant.SmsBwConstant;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.message.sms.common.SmsConstant;
import com.winhxd.b2c.message.sms.model.SmsReturn;
import com.winhxd.b2c.message.sms.enums.SmsReturnStatusEnum;
import com.winhxd.b2c.message.sms.enums.SmsSupplierEnum;
import com.winhxd.b2c.message.sms.enums.SmsTypeEnum;
import com.winhxd.b2c.message.utils.HttpClientUtil;
import com.winhxd.b2c.message.utils.SpringContextUtil;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 百悟平台发送短信
 * 
 */
public class BwSmsProcess {
	private static Logger logger = LoggerFactory.getLogger(BwSmsProcess.class);


	private BwSmsProcess() {
		// 构造私有
	}


	/**
	 * 发送消息
	 * @param mobile
	 * @param content
	 * @param type
	 * @return
	 */
	public static SmsReturn send(String mobile, String content , int type, String grp){
		SmsReturn result = null;

		SmsSupplierEnum smsSupplierEnum = null;

		//行业通道
		if(SmsTypeEnum.VERIFICATION.getType()==type){
			smsSupplierEnum = SmsSupplierEnum.getSmsSupplierEnumByParam(grp);
			result = BwSmsProcess.sendTextMsg(smsSupplierEnum,mobile,content);
			//语音通道
		}else if(SmsTypeEnum.VOICE.getType()==type){
			smsSupplierEnum = SmsSupplierEnum.getSmsSupplierEnumByParam(grp);
			result = BwSmsProcess.sendVoiceMsg(smsSupplierEnum,mobile,content);
			//营销通道
		}else{
			smsSupplierEnum = SmsSupplierEnum.getSmsSupplierEnumByParam(grp);
			//百悟营销通道 必须加上 “回TD退订”
			String contentStr = content+" 回TD退订";
			result = BwSmsProcess.sendTextMsg(smsSupplierEnum,mobile,contentStr);
		}
		return  result;
	}

	/**
	 * 带返回 结果信息对象 的短信发送
	 * 
	 * @param mobile 发信发送的目的号码.多个号码之间用半角逗号隔开
	 * @param content 短信的内容
	 * @return SMSReturn 短信发送返回信息对象
	 */
	protected static SmsReturn sendTextMsg(SmsSupplierEnum smsSupplier, String mobile, String content) {
		SmsReturn smsReturn = null;
		try {
			logger.info("调用百悟短信接口开始......");
			logger.info("类型：验证码短信短信。手机号：" + mobile + ",短信内容content：" + content);
			logger.info(smsSupplier.getAccount() + "," + smsSupplier.getUrl());

			//获取手机数量m
			String[] arrayMoile = mobile.split(",");

			//定义msgId
			String msgId = UUID.randomUUID().toString();

			NameValuePair[] data ={
					new NameValuePair(SmsBwConstant.KEY_ACCOUNT, smsSupplier.getAccount()),
					new NameValuePair(SmsBwConstant.KEY_PSWD, smsSupplier.getPwd()),
					new NameValuePair(SmsBwConstant.KEY_BUSINESS,smsSupplier.getBusinessCode()),
					new NameValuePair(SmsBwConstant.KEY_MOBILE,mobile),
					new NameValuePair(SmsBwConstant.KEY_CONTENT,content),

					//以下俩参数可为空但是属性不能少
					new NameValuePair(SmsBwConstant.KEY_MSG_ID, SpringContextUtil.getActiveProfile()+"|"+msgId),
					new NameValuePair(SmsBwConstant.KEY_EXT,"")
			};
			String rs = HttpClientUtil.postSend(smsSupplier.getUrl(), "", data,SmsConstant.URLDECODER_GBK, SmsConstant.URLDECODER_UTF8);
			smsReturn = analysisReturn(smsSupplier.getCode(),rs,arrayMoile.length);
			smsReturn.setMsgid(msgId);
		} catch (Exception e) {
			smsReturn = new SmsReturn();
			smsReturn.setStatus(SmsReturnStatusEnum.HTTPCLIENTERROR);
			logger.error("百悟短信发送结果异常。", e);
		}
		return smsReturn;
	}



	/**
	 * 发送语音短信验证码
	 *
	 * @param mobile 被叫号码（手机号或者座机）,座机号必须有区号,座机号格式(010-87654390)，区号和
	 * 				电话号码使用英文中划线(-)分割
	 * @param content 验证码内容，为数字和英文字母(英文字母小写)，长度4-8位
	 * @return SMSReturn 短信发送返回信息对象
	 */
	protected static SmsReturn sendVoiceMsg(SmsSupplierEnum smsSupplier,String mobile, String content) {
		SmsReturn smsReturn = null;
		try {
			logger.info("调用百悟语音验证码接口开始......");
			logger.info("类型：语音短信验证码。被叫号码：" + mobile + ",短信内容content：" + content);
			logger.info(smsSupplier.getAccount() + "," + smsSupplier.getUrl());

			String mttime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

			//获取字符串中的最后的数字
            content =  content.replaceAll(".*[^\\d](?=(\\d+))","");

			//验证码4到6位
			if(content!=null&&content.trim().length()<=SmsBwConstant.CODE_MAX_SIZE&&content.trim().length()>=SmsBwConstant.CODE_MIN_SIZE){

				NameValuePair[] data ={
						new NameValuePair(SmsBwConstant.VOICE_KEY_ACCOUNTSID, smsSupplier.getAccount()),
						new NameValuePair(SmsBwConstant.VOICE_KEY_SIGNATURE,md5Digest(smsSupplier.getAccount()+ md5Digest(smsSupplier.getPwd())+mttime)),
						new NameValuePair(SmsBwConstant.VOICE_KEY_OPERATYPE, SmsBwConstant.OPERATYPE_CONTENT),
						new NameValuePair(SmsBwConstant.VOICE_KEY_SERVICECODE,smsSupplier.getBusinessCode()),
						new NameValuePair(SmsBwConstant.VOICE_KEY_VOICECODE,content),
						new NameValuePair(SmsBwConstant.VOICE_KEY_DESTNUMBER,mobile),
						new NameValuePair(SmsBwConstant.VOICE_KEY_FETCHDATE,mttime),

						//自定义字符串，长度不可超过1000，会在状态报告推送或拉取时原样返回
						new NameValuePair(SmsBwConstant.VOICE_KEY_OTHER,SpringContextUtil.getActiveProfile()),
				};
				String rs = HttpClientUtil.postSend(smsSupplier.getUrl(), "", data,SmsConstant.URLDECODER_GBK,SmsConstant.URLDECODER_UTF8);
				smsReturn = analysisVoiceReturn(smsSupplier.getCode(),rs);

				Map<String, Object> obj = JsonUtil.parseJSONObject(rs);
				String msgId = (String) obj.get("callId");
				smsReturn.setMsgid(msgId);
			}else{
				smsReturn = new SmsReturn();
				smsReturn.setStatus(SmsReturnStatusEnum.BW_VOICE_ERROR_100202);
			}
		} catch (Exception e) {
			smsReturn = new SmsReturn();
			smsReturn.setStatus(SmsReturnStatusEnum.HTTPCLIENTERROR);
			logger.error("百悟短信发送结果异常。", e);
		}
		return smsReturn;
	}





	public static void main(String[] args) throws Exception {

        String message = "【惠下单】10月首单大礼：亲爱的店主朋友，泰恒达酒水批发部恢复供货，限时促销活动开始咯。惠下单订购泰恒达产品满200元，" +
                "加专属惠下单小助理为好友并提供订单截图，就可领取5元微信红包。另外还有10月的首单券，还在等什么呢，" +
                "还有更多活动在惠下单等你哟。回T退订";
        String mobile = "13810219241";
        String content = "发个梵蒂冈梵蒂冈";
        SmsReturn smsReturn = sendTextMsg(SmsSupplierEnum.outlet_verification_bw,mobile, content);
        //analysisReturn("");
       System.out.printf("返回结果"+ JsonUtil.toJSONString(smsReturn));


//		String textContent = "dev|c4fc4a25-5729-4dac-ab31-210aff0158ed";
//		String active = textContent.split("\\|")[0];
//		String msgId = textContent.split("\\|")[1];
//		System.out.printf(active+","+msgId);
	}


	/**
	 * 解析短信发送结果
	 * 
	 * @param rs 短信发送返回结果
	 * @return SmsReturn 短信发送返回对象
	 */
	public static SmsReturn analysisReturn(String code,String rs,int size) {
		SmsReturn smsReturn = new SmsReturn();
		if (StringUtils.isNotBlank(rs)) {
			String tempStr = "#";
			if(rs.equals(SmsReturnStatusEnum.SUCCESS.getStatusCode()+tempStr+size)){
				smsReturn.setStatus(SmsReturnStatusEnum.SUCCESS);
				return  smsReturn;
			}

			for (SmsReturnStatusEnum status : SmsReturnStatusEnum.values()) {
				if (status.getStatusCode().equals(code+"_"+rs)) {
					smsReturn.setStatus(status);
					break;
				}
			}
		}
		return smsReturn;
	}

	/**
	 * 解析语音短信发送结果
	 *
	 * @param rs 短信发送返回结果
	 * @return SmsReturn 短信发送返回对象
	 */
	public static SmsReturn analysisVoiceReturn(String code,String rs) {
		SmsReturn smsReturn = new SmsReturn();
		if (StringUtils.isNotBlank(rs)) {
			Map<String, Object> obj = JsonUtil.parseJSONObject(rs);
			String reqCode = (String) obj.get("respCode");
            if("000000".equals(reqCode)){
                smsReturn.setStatus(SmsReturnStatusEnum.SUCCESS);
                return smsReturn;
            }
			for (SmsReturnStatusEnum status : SmsReturnStatusEnum.values()) {
                if (status.getStatusCode().equals(code+"_"+reqCode)) {
                    smsReturn.setStatus(status);
                    break;
                }
			}
		}
		return smsReturn;
	}



	private static String md5Digest(String str) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
			char[] charArray = str.toCharArray();
			byte[] byteArray = new byte[charArray.length];
			for (int i = 0; i < charArray.length; i++) {
				byteArray[i] = (byte) charArray[i];
			}
			byte[] md5Bytes = md5.digest(byteArray);
			StringBuilder hexValue = new StringBuilder();
			for (int i = 0; i < md5Bytes.length; i++) {
				int val = (md5Bytes[i]) & 0xff;
				if (val < 16) {
					hexValue.append("0");
				}
				hexValue.append(Integer.toHexString(val));
			}
			return hexValue.toString();
		} catch (Exception e) {
			logger.error("加密异常", e);
			return "";
		}
	}

}
